//
//  PKRootViewController.m
//  PianKe
//
//  Created by lanou on 15/12/21.
//  Copyright © 2015年 KFC. All rights reserved.
//

#import "PKRootViewController.h"
#import "PKRootRightViewController.h"
#import "PKRadioMainViewController.h"
#import "PKLoginViewController.h"
#import "PKPersonModel.h"
#import "PKHomePageMainViewController.h"
#import "PKSearchViewController.h"
@interface PKRootViewController () <UITableViewDataSource,UITableViewDelegate>

@property (retain, nonatomic) PKRootRightViewController *rightVC;
// 数据源数组
@property (retain, nonatomic) NSArray *dataSource;

@property (retain, nonatomic) UITableView *tableView;

@property (retain, nonatomic) UINavigationController *naviController;

@end

@implementation PKRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    self.view.backgroundColor = [UIColor grayColor];
    
    // 创建右侧视图rightVC, 把rightVC添加到根视图上面
    // 首页是电台:
    self.rightVC = [[PKHomePageMainViewController alloc] init];
    _naviController = [[UINavigationController alloc] initWithRootViewController:_rightVC];  // 添加到导航视图控制器
    // 隐藏系统的导航栏 (我们用自定义的)
     _naviController.navigationBar.hidden = YES;
    
    // 3D阴影效果
    _naviController.view.layer.shadowColor = [[UIColor blackColor]CGColor];
    _naviController.view.layer.shadowOffset = CGSizeMake(-2,-8);
    _naviController.view.layer.shadowOpacity = 1;

    
    // 获取本地的时间:
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    // 设置时间显示的格式:
    [formatter setDateFormat:@"dd/MMM."];
    NSString *str = [formatter stringFromDate:date];
    NSLog(@"%@",str);
    self.rightVC.titleName = str;
    
    
    
    // 防止rightVC被销毁后,但是view没有被销毁,但是view上的按钮无法交互 ,可以把控制器添加为子控制器
    // 或者把控制器作为属性 (引用计数+1)
    // [self addChildViewController:self.rightVC];
    //[self.view addSubview:self.rightVC.view];

    [self.view addSubview:self.naviController.view];
    
    // 创建一个数据源数组
    _dataSource = @[@"首页",@"电台",@"阅读",@"社区",@"良品"];
    // 创建显示模块标题的列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 160*kHeightBase, kScreenWidth - 50*kWidthBase, kScreenHeight - 160*kHeightBase) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight =  (kScreenHeight - 160*kHeightBase) / 5 ; // 设置每行的高度
    self.tableView.backgroundColor = [UIColor grayColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    
    // 创建tableView上方的视图
    [self addSubViews];
    
    // 把rightVC.view放到最上面
    [self.view bringSubviewToFront:self.naviController.view];
    
}



// 创建tableView 上方 的 视图控件
- (void)addSubViews
{
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0,20*kHeightBase, self.tableView.width, self.tableView.top - 20*kHeightBase)];
   // self.contentView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.contentView];
    
    // contentView上的控件
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10 * kWidthBase, 20 * kHeightBase, 50 * kWidthBase, 50 * kWidthBase)];
    self.headImageView.layer.cornerRadius  = self.headImageView.width / 2;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.backgroundColor = [UIColor whiteColor];
    self.headImageView.image = [UIImage imageNamed:@"touxiang"];
    [self.contentView addSubview:self.headImageView];
    
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.headImageView.right + 10 * kWidthBase, self.headImageView.top, self.contentView.width - self.headImageView.right - 20 * kWidthBase, self.headImageView.height)];
   // self.userNameLabel.backgroundColor = [UIColor whiteColor];
    self.userNameLabel.text = @"登录|注册";
    [self.contentView addSubview:self.userNameLabel];
    
    // 通过判断登陆状态,给控件赋值
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL state = [userDefaults boolForKey:@"状态"];
    if (state == YES) {
        NSString *useName = [userDefaults objectForKey:@"uname"];
        NSString *picUrl = [userDefaults objectForKey:@"icon"];
        _userNameLabel.text = useName;
        [_headImageView sd_setImageWithURL:[NSURL URLWithString:picUrl] placeholderImage:nil];
        [userDefaults setBool:YES forKey:@"状态"];
        
    }
    
    
    
    
    self.userNameButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.userNameButton.frame = self.userNameLabel.frame;
    [self.contentView addSubview:self.userNameButton];
    
    
    
    self.downLoadButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.downLoadButton.frame = CGRectMake(self.headImageView.left + 15 * kWidthBase, self.headImageView.bottom + 15 * kHeightBase, 20 * kWidthBase, 20 * kWidthBase);
    [self.downLoadButton setBackgroundImage: [UIImage imageNamed:@"xiazai"] forState:(UIControlStateNormal)];
    [self.contentView addSubview:self.downLoadButton];
    
    self.favouritaButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.favouritaButton.frame = CGRectMake(self.downLoadButton.right + (self.tableView.width - 2 * self.downLoadButton.left - 4 * self.downLoadButton.width) / 3, self.downLoadButton.top, self.downLoadButton.width, self.downLoadButton.height);
    [self.favouritaButton setBackgroundImage:[UIImage imageNamed:@"favourite"] forState:(UIControlStateNormal)];
    [self.contentView addSubview:self.favouritaButton];
 
    self.messageButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.messageButton.frame = CGRectMake(self.favouritaButton.right + (self.tableView.width - 2 * self.downLoadButton.left - 4 * self.downLoadButton.width) / 3, self.favouritaButton.top, self.favouritaButton.width, self.favouritaButton.height);
    [self.messageButton setBackgroundImage:[UIImage imageNamed:@"liuyan"] forState:(UIControlStateNormal)];
    [self.contentView addSubview:self.messageButton];
    
    self.searchButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.searchButton.frame = CGRectMake(self.messageButton.right + (self.tableView.width - 2 * self.downLoadButton.left - 4 * self.downLoadButton.width) / 3, self.favouritaButton.top, self.favouritaButton.width, self.favouritaButton.height);
    [self.searchButton setBackgroundImage:[UIImage imageNamed:@"iconfont-sousuo"] forState:(UIControlStateNormal)];
    [self.contentView addSubview:self.searchButton];
    [self.searchButton addTarget:self action:@selector(searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    

    
    // 添加点击登录|注册按钮的方法
    [self.userNameButton addTarget:self action:@selector(loginOrRegister:) forControlEvents:(UIControlEventTouchUpInside)];

    // 接受通知,给登陆等控件赋值
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificatinAction:) name:@"用户信息" object:nil];
    
    
}

- (void)notificatinAction:(NSNotification *)noti
{
    NSDictionary *dic = noti.userInfo;
    PKPersonModel *personModel = dic[@"用户信息"];
    [_headImageView sd_setImageWithURL:[NSURL URLWithString:personModel.icon] placeholderImage:nil];
    _userNameLabel.text = personModel.uname;
}


#pragma mark ---- tableview的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    cell.backgroundColor = [UIColor grayColor];
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(4,2);
    cell.layer.borderColor = [[UIColor blackColor]CGColor];
    cell.layer.borderWidth = 1;
    // 修改shadow的透明度,不为0就能显示出来
    cell.layer.shadowOpacity = 1;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 展示数据
    cell.textLabel.text = self.dataSource[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 创建一个数组,保存类名
    NSArray *classArray = @[@"PKHomePageMainViewController",@"PKRadioMainViewController",@"PKReadMainViewController",@"PKCommunityMainViewController",@"PKProductsMainViewController"];
    
    // iskindOfClass 判断对象是否属于这个类或者这个类的子类
    // isMemberOfClass 判断对象是否属于这个类
    // 判断点击的是不是同一个cell,判断_rightVC是不是和之前的那个一致,一致就不走下面的操作,直接返回空就行
//    if ([_rightVC isMemberOfClass:NSClassFromString(classArray[indexPath.row])]) {
//        
//        NSLog(@"重复点击");
//        return;
//        
//    }
    

    // 每次点击tabelView创建一个新的rightVC,就把老的View移出掉
    // 移除掉的是导航视图控制器的view
    [_naviController.view removeFromSuperview];

     self.tableView.userInteractionEnabled = NO;
    
    // NSClassFromString(classArray[indexPath.row] 取出类 (字符串转类)
    _rightVC = [[NSClassFromString(classArray[indexPath.row]) alloc] init];
    // 创建导航控制器
    _naviController = [[UINavigationController alloc] initWithRootViewController:_rightVC];
    _naviController.navigationBar.hidden = YES; // 隐藏导航栏
    
    _naviController.view.frame = CGRectMake(kScreenWidth - 50*kWidthBase, 0, kScreenWidth, kScreenHeight);
    // 3D阴影效果
    _naviController.view.layer.shadowColor = [[UIColor blackColor]CGColor];
     _naviController.view.layer.shadowOffset = CGSizeMake(-2,-8);
    _naviController.view.layer.shadowOpacity = 1;
    [self.view addSubview:self.naviController.view];
    
    
    // 给rightVC的headView的label赋值
    
    if (indexPath.row == 0) {
        
        // 说明是首页
        // 获取本地的时间:
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        // 设置时间显示的格式:
        [formatter setDateFormat:@"dd/MMM."];
        NSString *str = [formatter stringFromDate:date];
        
        _rightVC.titleName = str;
        
    } else {
        
         _rightVC.titleName = _dataSource[indexPath.row];
        
    }
    
    
    [UIView animateWithDuration:1 animations:^{
       
        _naviController.view.frame  = _naviController.view.bounds;
       
    } completion:^(BOOL finished) {
        
        self.tableView.userInteractionEnabled = YES;
        
    }] ;
   

    
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGPoint center = cell.center;
    CGPoint tempCenter = center;
    center.x += 100;
    cell.center = center;
    
    for (int i = 0; i < _dataSource.count;i++) {
        
        [UIView animateWithDuration:1 delay:0.35*i usingSpringWithDamping:0.8 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
            cell.center = tempCenter;

        } completion:nil];
    }
    
}





#pragma mark  ------ 跳转到登录|注册界面
- (void)loginOrRegister:(UIButton *)button
{
    // 判断登陆状态
    // 通过判断登陆状态,给控件赋值
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL state = [userDefaults boolForKey:@"状态"];
    if (state == YES) {
        
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"提示" contentText:@"确定要注销?" leftButtonTitle:@"NO" rightButtonTitle:@"YES"];
        [alert show];

        alert.rightBlock = ^() {
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            BOOL state = [userDefaults boolForKey:@"状态"];
            state = NO;
            [userDefaults setBool:state forKey:@"状态"];
            [userDefaults synchronize];
            _userNameLabel.text = @"登录|注册";
            _headImageView.image = [UIImage imageNamed:@"touxiang"];
            NSLog(@"注销成功");
            
            
        };

        
    } else {
        
        PKLoginViewController *loginVC = [[PKLoginViewController alloc] init];
        
        // 给注册页面 加个导航栏 ,才能 让注册按钮push到注册页面
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        // 再隐藏导航栏
        navc.navigationBarHidden = YES;
        
        [self presentViewController:navc animated:YES completion:nil];
        
    }
    
    
    
}

#pragma mark ---- 按钮方法
- (void)searchAction:(UIButton *)sender
{
    PKSearchViewController *searchVC = [[PKSearchViewController alloc] init];
    
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:searchVC];
    
    navc.navigationBarHidden = YES;
    
    [self presentViewController:navc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
